(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.fxRate.uploadController', uploadController);
	uploadController.$inject = [ '$scope', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService' ];
	function uploadController($scope, Constants, modalService, gridService, layoutConfig, validatorConfig, authService) {
		var ctrl = this, fxRateInfo = $scope.$stateParams.params;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.fxRateUpload = {};
		
		ctrl.init = function() {
			var params = {
				fxrateId : fxRateInfo.fxrateId
			};
			authService.upload(params).then(function(response) {
				ctrl.fxRateUpload = response.data || fxRateInfo;
				ctrl.fxRateUpload.fileFormat = '<fxRates site="BANKPT" baseCcy="USD">\n' +
				'   <fxRate ccy="EUR"  book="0.36" sell="1.12"  buy="2.13" custom="2.13" min="2.13" max="2.13" /> \n'+
				'   <fxRate ccy="GBP"  book="0.8" sell="0.81"  buy="0.92" custom="2.13" min="2.13" max="2.13" /> \n'+
				'</fxRates>';
				ctrl.fxRateUpload.description = 'cda.fxrateupload.desc';
			});
		};
		
		ctrl.showCreateButton = function(){
			if(ctrl.fxRateUpload && ctrl.fxRateUpload.lockFlag == 'Y'){
				return true;
			}else{
				return false;
			};
		};
		
		ctrl.uploadSend = function() {
			if(!ctrl.fxRateUpload.uploadFiles || !ctrl.fxRateUpload.uploadFiles[0] || !ctrl.fxRateUpload.uploadFiles[0].docFileName){
				modalService.openErrorDialogs({
					'messages' : ['cda.fxrateupload.uploadfiles.required']
				});
				return;
			}
			var fileName = ctrl.fxRateUpload.uploadFiles[0].docFileName;
			ctrl.fxRateUpload.docId = ctrl.fxRateUpload.uploadFiles[0].docId;
			var position = fileName.lastIndexOf(".");
			var fmt = fileName.substring(position + 1, fileName.length);
			if (fmt.toLowerCase() != "xml") {
				modalService.openErrorDialogs({
					'messages' : ['fxrate.file.format.invalid']
				});         
			} else {			
				return authService.uploadSend(ctrl.fxRateUpload).then(uploadSuccessful, uploadFailed);
			}
		};
		
		function uploadSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'messages.fxrate.upload.success' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.fxRate.upload');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.fxrateupload.list',
					'state' : 'cda.fxRateUpload.list',
					'params' : {}
				}]
			});
		}
		
		function uploadFailed(response) {
			if(!response.error || response.error == ''){
				response.error = 'fxrate.file.content.invalid';
			}
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);